﻿using System;
using System.Diagnostics;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;

using LightReader.UserService;

namespace LightReader
{
	public partial class Register : UserControl
	{
		public Register()
		{
			// Required to initialize variables
			InitializeComponent();

            setupEventHandlers();
        }

        #region Event Handlers
        private void submitButton_Click(object sender, RoutedEventArgs e)
        {
            if (validateFields())
            {
                // service call
                UserServiceClient usc = new UserServiceClient();
                usc.AddUserCompleted += new EventHandler<AddUserCompletedEventArgs>(usc_AddUserCompleted);
                usc.AddUserAsync(userNameTextbox.Text, SecurityHelper.ComputeHash(passwordConfirmTextbox.Text), emailAddressTextbox.Text);
            }
            else
            {
                errorText.Visibility = Visibility.Visible;
                errorText.Text = "Please make sure you enter a username, email address and that the passwords match.";
            }
        }

        public event EventHandler<UserAddedEventArgs> UserAdded;
        void usc_AddUserCompleted(object sender, AddUserCompletedEventArgs e)
        {                        
            // Thank you page
            if (e.Result == null)
            {
                UserAddedEventArgs uaea = new UserAddedEventArgs();
                uaea.User = e.Result;
                OnUserAdded(uaea);
            }
            else
            {
                Debug.WriteLine(e.Error.ToString());
            }
        }

        protected virtual void OnUserAdded(UserAddedEventArgs e)
        {
            EventHandler<UserAddedEventArgs> handler = UserAdded;
            if (handler != null)
            {
                handler(this, e);
            }
        }

        private void cancelButton_Click(object sender, RoutedEventArgs e)
        {
            // TODO: prompt the user before leaving the register page
            NavigationHelper.Navigate(new SplashPage());
        }

        private void userNameTextbox_LostFocus(object sender, RoutedEventArgs e)
        {
            // check to see if this username already exists
            if (userNameTextbox.Text.Length > 0)
            {
                UserServiceClient us = new UserServiceClient();
                us.DoesUserExistCompleted += new EventHandler<DoesUserExistCompletedEventArgs>(us_DoesUserExistCompleted);
                us.DoesUserExistAsync(userNameTextbox.Text);
                
            }
        }

        void us_DoesUserExistCompleted(object sender, DoesUserExistCompletedEventArgs e)
        {
            if (e.Result == true)
            {
                errorText.Visibility = Visibility.Visible;
                errorText.Text = "Sorry, that username is being used.";
            }
            else
            {
                errorText.Visibility = Visibility.Collapsed;
            }
        }
        #endregion

        #region Helper methods
        private void setupEventHandlers()
        {
            userNameTextbox.LostFocus += new RoutedEventHandler(userNameTextbox_LostFocus);
            submitButton.Click += new RoutedEventHandler(submitButton_Click);
            cancelButton.Click += new RoutedEventHandler(cancelButton_Click);
        }

        private bool validateFields()
        {
            bool returnVal = false;

            // make sure all fields are populated
            // make sure email is in the correct format
            // make sure the two password fields match
            returnVal = allFieldsPopulated() & isEmailInCorrectFormat() & doPasswordsMatch();

            return returnVal;
        }

        private bool doPasswordsMatch()
        {
            bool returnVal = false;
            if (passwordTextbox.Text == passwordConfirmTextbox.Text)
            {
                returnVal = true;
            }
            return returnVal;
        }

        private bool isEmailInCorrectFormat()
        {
            bool returnVal = false;

            // see http://www.regular-expressions.info/email.html for regex explanation
            Regex r = new Regex(@"^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$", RegexOptions.IgnoreCase);
            if (r.IsMatch(emailAddressTextbox.Text))
            {
                returnVal = true;
            }

            return returnVal;
        }

        private bool allFieldsPopulated()
        {
            bool returnVal = false;
            if(
                (userNameTextbox.Text.Length > 0) && 
                (emailAddressTextbox.Text.Length  > 0) && 
                (passwordTextbox.Text.Length > 0) && 
                (passwordConfirmTextbox.Text.Length > 0)) {

                    returnVal = true;
            }
            return returnVal;
        }
        #endregion
    }

    // TODO - move
    public class UserAddedEventArgs : EventArgs
    {
        public User User { get; set; }
    }
}